import re
from dataclasses import dataclass
from datetime import datetime
from typing import List, Optional

import asyncio

import httpx
import requests
from aiogram import Bot, types, F
# from app.keyboards import main_kb, inspection_kb, completion, data_conteiner, start_kb
# from utilites.utilits_bot import coincidence
from aiogram import Router
from aiogram.fsm.context import FSMContext
# from models import get_users, init, get_user, create_user, create_conteiner, get_first_conteiner, ImagesConteiner, get_conteiner, StatusConteiner
from aiogram.types import Message
from asgiref.sync import sync_to_async
from icecream import ic

import dbconnect
import http_rest
from app.keyboards import tech_actions, ref_opt, ref_control, ref_control2, ref_temp, ref_inspection, ref_cancel_not
from form.forms import Stat
from start_bot import AUTHORS
from utilites.bot_util import cont_read, ocr, inform_cont, cont_read10, curent_date, a_send_data

from utilites.my_exp import queue

router = Router()



@dataclass
class ContainerData:
    number_cont: str
    ref_mon_img: List[str]
    temperature: Optional[int]
    errors_ref: List[str]
    destroyed: List[str]


ref_stats = '''
        Конетйнер: {ContNum}
    ________________________________
        Дата: {StatusDate}
        Last temp: {LastTemp}
        Req temp: {ReqTemp}
        New temp: {NewTemp}
    ________________________________
        Last errors: {LastErr}
        errors: {NewErr}
    ________________________________
        Статус подключения: {Status}
        GPS: {LastGPS}
    ++++++++++++++++++++++++++++++++
        Груз: {Cargo}
    '''


async def canceling(message: Message, state: FSMContext):
    if message.text == 'Отмена заявки':
        await state.clear()
        await message.answer('Выберите действие', reply_markup=tech_actions)
    else:
        return True


async def telegram_photo_load(file_path: str, message: Message):
    photo = message.photo[-1].file_id
    await message.bot.download(photo, file_path)


#@router.message(F.text == 'Осмотр конетейнеров', canceling)
#async def vision_conteiners(message: Message, state: FSMContext):
    #await message.delete()
    #await state.set_state(Stat.number_cont)
    #bot_message = await message.answer('Введите номер контейнера (последние 5 - 4 цифры)', reply_markup=ref_opt)
    #await state.set_data({'message_id': bot_message.message_id})


@router.callback_query(F.data == 'Inspection_cont_rf')
async def vision_conteiners(callback_query: types.CallbackQuery, state: FSMContext):
    await callback_query.message.delete()
    await state.set_state(Stat.number_cont)
    bot_message = await callback_query.message.answer('Введите номер контейнера (последние 5 - 4 цифры)', reply_markup=ref_opt)
    await state.set_data({'message_id': bot_message.message_id})


async def search_cont_by_four_numbers(numbers, Fulltext=False):
    await asyncio.sleep(0.1)
    Cont = http_rest.ContainerInfo()
    temp = await Cont.SearchByNum2(numbers)
    # ic(temp)
    # if Fulltext == False:
    #     text_request = {"select": "Контейнер/Description,Контейнер/Ref_Key",
    #                     "filter": "endswith(Контейнер/Description,`" + numbers + "`) eq true",
    #                     "expand": "Контейнер"}
    # else:
    #     text_request = {"select": "Контейнер/Description,Контейнер/Ref_Key",
    #                     "filter": "Контейнер/Description eq`" + numbers + "`",
    #                     "expand": "Контейнер"}
    # new_test = await sync_to_async(http_rest.send_odata_get)("AccumulationRegister_КонтейнерыНаТерминале/Balance", text_request)
    # data = new_test.json()
    return temp


async def conteiner_detect(message: Message, state: FSMContext):
    if message.text:
        numbers = await cont_read(message.text)
    else:
        numbers = False
    if numbers:
        return True
    elif message.photo:
        photo = message.photo[-1].file_id
        file_path = f'temp/{photo}.jpg'
        await telegram_photo_load(file_path, message)
        numbers = await ocr(file_path)
        await state.set_state(Stat.number_cont)
        await message.answer(f'Это не верный номер контейнера это картинка {numbers}', reply_markup=ref_opt)
    # elif message.text == 'Отмена заявки':
    #     await state.clear()
    #     await message.answer('Вы отменили действие', reply_markup=tech_actions)
    else:
        return False


async def conteiner_detect_out(message: Message, state: FSMContext):
    numbers = await cont_read(message.text)
    if numbers:
        return False
    elif message.text == 'Отмена заявки':
        await message.delete()
        await state.clear()
        await message.answer('Выберите действие', reply_markup=tech_actions)
    else:
        await message.delete()
        await state.set_state(Stat.number_cont)
        bot_message = await message.answer('Это не верный номер контейнера')
        await asyncio.sleep(5)
        await bot_message.delete()


@router.message(Stat.number_cont, conteiner_detect, canceling)
async def number_cont(message: Message, state: FSMContext):
    bot_data = await state.get_data()
    try:
        await message.bot.delete_message(message.chat.id, bot_data['message_id'])
    except:
        pass
    await message.delete()
    datas = await search_cont_by_four_numbers(message.text)

    # Общие переменные и запросы, которые не зависят от условий
    inline_keyboard = []
    temp_dict = {}
    async with httpx.AsyncClient() as client:
        auth = (dbconnect.http_login, dbconnect.http_pwd)
        await message.bot.send_chat_action(message.chat.id, 'typing')
        await asyncio.sleep(0.1)
        if datas.get('Contlist') is not None:
            await state.clear()
            await state.set_state(Stat.number_cont)
            for i in datas['Contlist']:
                temp_dict[i['Description']] = i['Ref_Key']
                if i['Type'] in ['40RF', '45R1', '45RT', '45RH', '45RF', '45RC', '45T1', '45T2', '45T3', '45T4', '45T5', '45T6', '45P1', '45P2', '45P3']:
                    inline_keyboard.append(
                        [types.InlineKeyboardButton(text=i['Description'], callback_data=i['Description'])]
                    )

        elif datas.get('ContNum') is not None:
            temp_dict[datas.get('ContNum')] = datas.get('RefKey')
            if datas['ContType'] in ['40RF', '45R1', '45RT', '45RH', '45RF', '45RC', '45T1', '45T2', '45T3', '45T4', '45T5', '45T6', '45P1', '45P2', '45P3']:
                inline_keyboard = [
                    [types.InlineKeyboardButton(text=datas.get('ContNum'), callback_data=datas.get('ContNum'))]
                ]

    if not inline_keyboard:
        await state.set_state(Stat.number_cont)
        bot_message = await message.answer('Реф контейнер не найден', reply_markup=ref_opt)
        await state.update_data({'message_id': bot_message.message_id})
    else:
        await state.set_data(temp_dict)
        cont_keyboard = types.InlineKeyboardMarkup(inline_keyboard=inline_keyboard)
        await message.answer('Выберете контейнер', reply_markup=cont_keyboard)


async def number_conteiners(data):
    numbers = await cont_read10(data)
    if numbers:
        return True
    else:
        return False


async def filter_midl1(callback_query: types.CallbackQuery, state: FSMContext):
    if callback_query.data in ['inspection', 'confirm_temp', 'temp', 'minus_temp', 'plus_temp', 'minus_temp-0.1',
                               'plus_temp-0.1', 'save_temp', 'erorrs_ref', 'connect', 'cancel_ref', 'cancel_appl',
                               'save_data', 'save_ref_menu', 'back_ref_menu',]:
        return True
    elif await number_conteiners(callback_query.data):
        return True
    elif callback_query.data == 'canceling_exercise':
        await state.clear()
        await callback_query.message.delete()
        await callback_query.message.answer('Выберите действие', reply_markup=tech_actions)
    elif callback_query.data == 'can_exer':
        await vision_conteiners(callback_query, state, ref_temp, edit=True)

    return False


@router.callback_query(filter_midl1)
async def number_conteiners_callback(callback_query: types.CallbackQuery, state: FSMContext):
    dict_ = await state.get_data()

    ic(callback_query.data)
    await callback_query.message.bot.send_chat_action(callback_query.message.chat.id, 'typing')
    if await number_conteiners(callback_query.data):
        await callback_query.message.delete()
        ref_key = dict_[callback_query.data]
        cont = http_rest.ContainerInfo()
        cont.RefKey = ref_key
        cont.ContNum = callback_query.data
        date_conteiner = await cont.FillContainerInfo()
        await state.set_data(date_conteiner)
        await state.set_state(Stat.number_cont)
        await vision_conteiners(callback_query, state, ref_control2 if date_conteiner['Status'] != '⚡' else ref_control)
        # await callback_query.message.answer(ref_stat, reply_markup=ref_control2 if date_conteiner['Status'] != '⚡' else ref_control)
    elif callback_query.data == 'inspection':
        await vision_conteiners(callback_query, state, ref_inspection, edit=True)
    elif callback_query.data == 'confirm_temp':
        # await state.set_state(Stat.temperature)

        dict_['NewTemp'] = dict_['ReqTemp']
        await state.set_data(dict_)
        await vision_conteiners(callback_query, state, ref_temp, edit=True)
    elif callback_query.data == 'temp':
        await state.set_state(Stat.temperature)
        bot_message = await callback_query.message.edit_text('Укажите температуру', reply_markup=ref_cancel_not)
        dict_['message_id'] = bot_message.message_id
        await state.set_data(dict_)
    elif callback_query.data == 'minus_temp':
        if dict_['NewTemp'] == 'НЕТ':
            dict_['NewTemp'] = dict_['ReqTemp']
        dict_['NewTemp'] = str(round(float(dict_['NewTemp']) - 1, 2))
        await state.set_data(dict_)
        await vision_conteiners(callback_query, state, ref_temp, edit=True)
    elif callback_query.data == 'plus_temp':
        if dict_['NewTemp'] == 'НЕТ':
            dict_['NewTemp'] = dict_['ReqTemp']
        dict_['NewTemp'] = str(round(float(dict_['NewTemp']) + 1, 2))
        await state.set_data(dict_)
        await vision_conteiners(callback_query, state, ref_temp, edit=True)
    elif callback_query.data == 'minus_temp-0.1':
        if dict_['NewTemp'] == 'НЕТ':
            dict_['NewTemp'] = dict_['ReqTemp']
        dict_['NewTemp'] = str(round(float(dict_['NewTemp']) - 0.1, 2))
        await state.set_data(dict_)
        await vision_conteiners(callback_query, state, ref_temp, edit=True)
    elif callback_query.data == 'plus_temp-0.1':
        if dict_['NewTemp'] == 'НЕТ':
            dict_['NewTemp'] = dict_['ReqTemp']
        dict_['NewTemp'] = str(round(float(dict_['NewTemp']) + 0.1, 2))
        await state.set_data(dict_)
        await vision_conteiners(callback_query, state, ref_temp, edit=True)
    elif callback_query.data == 'back_ref_menu':
        dict_ = await state.get_data()
        dict_['NewTemp'] = 'НЕТ'
        await state.set_state(Stat.edit_temp)
        await vision_conteiners(callback_query, state, ref_control2 if dict_['Status'] != '⚡' else ref_control,
                                edit=True)
    elif callback_query.data == 'save_ref_menu':
        dict_ = await state.get_data()
        await state.set_state(Stat.edit_temp)
        await vision_conteiners(callback_query, state, ref_control2 if dict_['Status'] != '⚡' else ref_control, edit=True)
    elif callback_query.data == 'save_temp':
        ic(dict_)
        await state.set_state(Stat.number_cont)
        await vision_conteiners(callback_query, state, ref_inspection, edit=True)
    elif callback_query.data == 'erorrs_ref':
        await callback_query.message.delete()
        await state.set_state(Stat.errors_ref)
        await callback_query.message.answer('Укажите ошибки', reply_markup=ref_cancel_not)
    elif callback_query.data == 'connect':
        await state.set_state(Stat.number_cont)
        if dict_['Status'] == '⚡':
            dict_['Status'] = '🔌'
            Action = 'Отключение'
        else:
            dict_['Status'] = '⚡'
            Action = 'Подключение'
        if dict_['NewTemp'] not in ['0', '0.0', None, '', 'НЕТ']:
            LastTemp = dict_['NewTemp']
        else:
            LastTemp = dict_['ReqTemp']
        date = await curent_date()
        date_obj = datetime.strptime(date, "%H:%M %d.%m.%Y")
        formatted_date = date_obj.strftime("%Y-%m-%dT%H:%M:%S")
        ic(dict_)
        long_text = dict(Date=formatted_date, ВидРаботыСРеф=Action,
                         ДатаВремя=formatted_date, Контейнер_Key=dict_['RefKey'],
                         ТемператураПеред=ic(str(dict_['NewTemp'])) if dict_['NewTemp'] != 'НЕТ' else ic(str(dict_['ReqTemp'])), ТемператураПосле=ic(str(dict_['NewTemp'])) if dict_['NewTemp'] != 'НЕТ' else ic(str(dict_['ReqTemp'])),
                         ТемператураНормативная=str(dict_['ReqTemp']), Автор=ic(AUTHORS[callback_query.from_user.id]),
                         Автор_Type="StandardODATA.Catalog_Сотрудники", Статус="Завершен",
                         Ответственный_Key=ic(AUTHORS[callback_query.from_user.id]), Комментарий="",
                         Сотрудник_Key=ic(AUTHORS[callback_query.from_user.id]))
        #await asyncio.sleep(0.1)
        #update_req = await http_rest.send_odata_post('Document_РаботаСРефКонтейнерами', long_text)
        #if update_req == 'Ошибка':
            #await callback_query.message.answer('Ошибка при отправке данных')
        send = asyncio.create_task(a_send_data(callback_query, state, long_text))
        await state.set_data(dict_)
        await vision_conteiners(callback_query, state, ref_control2 if dict_['Status'] != '⚡' else ref_control, edit=True)
    elif callback_query.data == 'cancel_ref':
        # await callback_query.message.delete()
        dict_ = await state.get_data()
        dict_['NewTemp'] = 'НЕТ'
        await state.set_data(dict_)
        await state.set_state(Stat.number_cont)
        await vision_conteiners(callback_query, state, ref_inspection, edit=True)
    elif callback_query.data == 'cancel_appl':

        await callback_query.bot.delete_message(callback_query.from_user.id, callback_query.message.message_id)

        await state.set_state(Stat.number_cont)
        bot_message = await callback_query.message.answer('Введите номер контейнера (4 цифры)', reply_markup=ref_opt)
        dict_['message_id'] = bot_message.message_id
        await state.set_data(dict_)
    elif callback_query.data == 'save_data':
        if dict_['Status'] == '⚡':
            dict_['Status'] = '🔌'
            Action = 'Отключение'
        else:
            dict_['Status'] = '⚡'
            Action = 'Подключение'
        if dict_['NewTemp'] not in ['0', '0.0', None, '', 'НЕТ']:
            LastTemp = dict_['NewTemp']
        else:
            LastTemp = dict_['ReqTemp']
        date = await curent_date()
        date_obj = datetime.strptime(date, "%H:%M %d.%m.%Y")
        formatted_date = date_obj.strftime("%Y-%m-%dT%H:%M:%S")
        ic(dict_)
        long_text = dict(Date=formatted_date, ВидРаботыСРеф=Action,
                         ДатаВремя=formatted_date, Контейнер_Key=dict_['RefKey'],
                         ТемператураПеред=str(LastTemp), ТемператураПосле=ic(str(dict_['NewTemp'])) if dict_['NewTemp'] != 'НЕТ' else ic(str(dict_['ReqTemp'])),
                         ТемператураНормативная=str(dict_['NewTemp']), Автор=ic(AUTHORS[callback_query.from_user.id]),
                         Автор_Type="StandardODATA.Catalog_Сотрудники", Статус="Завершен",
                         Ответственный_Key=ic(AUTHORS[callback_query.from_user.id]), Комментарий="",
                         Сотрудник_Key=ic(AUTHORS[callback_query.from_user.id]))
        #await asyncio.sleep(0.1)
        #update_req = await http_rest.send_odata_post('Document_РаботаСРефКонтейнерами', long_text)
        #if update_req == 'Ошибка':
            #await callback_query.message.answer('Ошибка при отправке данных')
        #send = asyncio.create_task(a_send_data(callback_query, state, long_text))

        await queue.add_task(a_send_data(callback_query, state, long_text))
        await state.set_state(Stat.number_cont)
        bot_message = await callback_query.message.edit_text('Введите номер контейнера (5 - 4 цифры)', reply_markup=ref_opt)
        dict_['message_id'] = bot_message.message_id
        await state.set_data(dict_)

    #     user_id = str(callback_query.from_user.id)
    #     # text_request = {"filter": "ИдентификаторТ eq `" + user_id + "`"}
    #     # request = await sync_to_async(http_rest.send_odata_get)("InformationRegister_ТелеграмПодписки", text_request)
    #     # data = request.json()
    #     # Тут еще следует поизучать
    #     dict_ = await state.get_data()
    #     dict_['Author_Key'] = AUTHORS[callback_query.from_user.id]
    #     ic(AUTHORS[callback_query.from_user.id])
    #     await state.set_data(dict_)
    #     await state.set_state(Stat.number_cont)
    #     await vision_conteiners(callback_query, state, ref_opt, send=True)
    # else:
    #     await state.set_state(Stat.number_cont)
    #     await callback_query.message.answer('Это не верный номер контейнера', reply_markup=tech_actions)


@router.message(Stat.number_cont, conteiner_detect_out, canceling)
async def number_cont_out(message: Message, state: FSMContext):
    await state.set_state(Stat.number_cont)


@router.message(Stat.ref_mon_img, canceling)
async def ref_mon_img(message: Message, state: FSMContext, bot: Bot):
    ic(message.text)
    if message.text == 'Завершить':
        await state.set_state(Stat.temperature)
        await message.answer('Укажите температуру')
    elif message.photo:
        await state.set_state(Stat.ref_mon_img)
        dict_ = await state.get_data()
        photo = message.photo[-1].file_id
        file_path = f'photos/{dict_["ContNum"]}{photo}.jpg'
        dict_['ref_mon_img'].append(file_path)
        await state.set_data(dict_)
        await message.bot.download(file=photo, destination=file_path)

        await message.answer('Загрузите референсную мониторинговую картинку', reply_markup=ref_opt)
    elif message.text != 'Завершить':
        await state.set_state(Stat.ref_mon_img)
        await message.answer('Не корректные данные', reply_markup=ref_opt)


async def is_temperature(message: Message, state: FSMContext):
    pattern = re.compile(r'^-?\d+(\.\d+)?$')
    if pattern.match(str(message.text)):
        return True
    elif message.text == 'Завершить':
        await state.set_state(Stat.errors_ref)
        await message.answer('Укажите ошибки', reply_markup=ref_opt)
    elif message.text == 'Отмена заявки':
        await message.delete()
        await state.clear()
        await message.answer('Заявка отменена', reply_markup=tech_actions)
    else:
        await state.set_state(Stat.temperature)
        await message.answer('Введены не корректные данные тепературы')
        return False


@router.message(Stat.temperature, is_temperature)
async def add_temp(message: Message, state: FSMContext):
    dict_ = await state.get_data()
    bot_message_id = dict_['message_id']
    await message.bot.delete_message(message.chat.id, bot_message_id)
    dict_['NewTemp'] = message.text
    await state.set_data(dict_)
    await message.bot.delete_message(message.chat.id, message.message_id)
    await vision_conteiners(message, state, ref_temp)
    # await message.answer(ref_stat, reply_markup=ref_control2 if dict_['Status'] != '⚡' else ref_control)


# @router.message(Stat.edit_temp, F.data == 'temp')
# async def edit_temp(message: Message, state: FSMContext):
#     global ref_stats
#     dict_ = await state.get_data()
#     dict_['NewTemp'] = message.text
#     ic(dict_)
#     await state.set_data(dict_)
#     await message.bot.delete_message(message.chat.id, message.message_id)
#     await state.set_state(Stat.temperature)
#     await vision_conteiners(message, state, ref_temp, options=Stat.temperature)
#     # await message.answer(ref_stat, reply_markup=ref_control2 if dict_['Status'] != '⚡' else ref_control)


@router.callback_query(F.data == 'reply_temp')
async def repy_temp(callback_query: types.CallbackQuery, state: FSMContext):
    if callback_query.data == 'reply_temp':
        await callback_query.message.delete()
        await state.set_state(Stat.temperature)
        await callback_query.message.answer(f'Укажите температуру', reply_markup=tech_actions)


@router.callback_query(F.data == 'confirm_temp')
async def temp_callback(callback_query: types.CallbackQuery, state: FSMContext):
    ic(callback_query)
    await state.set_state(Stat.errors_ref)
    await callback_query.message.answer('Укажите ошибки', reply_markup=ref_opt)


@router.message(Stat.errors_ref, canceling)
async def ref_mon_errors(message: Message, state: FSMContext):
    await message.delete()
    dict_ = await state.get_data()
    dict_['NewErr'] = message.text
    await state.set_data(dict_)

    await state.set_state(Stat.number_cont)
    await vision_conteiners(message, state, ref_inspection)


@router.message(Stat.cont_destroin, canceling)
async def ref_mon_img(message: Message, state: FSMContext):
    dict_ = await state.get_data()
    if message.text == 'Завершить':
        ic(await state.get_data())
        await state.clear()
        await message.answer('Выберете действие', reply_markup=tech_actions)
    elif message.text != 'Завершить':
        dict_['destroyed'].append(message.text)
        await state.set_data(dict_)
        await state.set_state(Stat.cont_destroin)
        info = await inform_cont(dict_)
        del dict_
        await message.answer(info, reply_markup=ref_opt)


async def vision_conteiners(message, state: FSMContext, ref_control: types.InlineKeyboardMarkup, send: bool = False,
                            edit=False, options=None):
    dict_ = await state.get_data()

    CronFlag = False
    CronFlag2 = False

    Cont = http_rest.ContainerInfo()
    ic(dict_)

    Cont.ContNum = dict_['ContNum']
    Cont.Cargo = dict_['Cargo']
    Cont.LastTemp = dict_['NewTemp'] if dict_['NewTemp'] not in ['0', '0.0', None, ''] else '0'
    Cont.ReqTemp = dict_['ReqTemp']
    Cont.NewTemp = dict_['NewTemp']
    Cont.NewErr = dict_['NewErr']
    Cont.LastErr = dict_['LastErr']
    Cont.LastViev = dict_['LastViev']
    Cont.RefKey = dict_['RefKey']
    Cont.Status = dict_['Status']
    Cont.StatusDate = dict_['StatusDate']
    Cont.LastGPS = dict_['LastGPS']
    ic(Cont.NewErr)
    StatusDate = await curent_date()

    Cont.RefJournalNum = dict_['RefJournalNum']

    RefJournalNum = dict_['RefJournalNum']
    ContNumberRefKey = Cont.RefKey
    text_request = {"filter": "Контейнер_Key eq guid`" + ContNumberRefKey + "`",
                    "expand": "Свойство",
                    "select": "Свойство/PredefinedDataName, ЗначениеСвойства"}
    new_test = await http_rest.send_odata_get(
        "InformationRegister_СведенияОКонтейнере_RecordType/SliceLast",
        text_request)
    data = new_test.json()

    # Cont.ReqTemp = 'НЕТ'
    flag = True
    for i in range(len(data['value'])):
        if data['value'][i]['Свойство']['PredefinedDataName'] == 'Пустой':
            if data['value'][i]['ЗначениеСвойства'] != 'false':
                await message.answer(
                    text='Контейнер пустой', parse_mode='HTML')
                flag = False
                break
        elif data['value'][i]['Свойство']['PredefinedDataName'] == 'ТемпературныйРежим':
            Cont.ReqTemp = data['value'][i]['ЗначениеСвойства'] if data['value'][i][
                                                                       'ЗначениеСвойства'] != '0' else 'НЕТ'
        elif data['value'][i]['Свойство']['PredefinedDataName'] == 'Груз':
            Cont.Cargo = data['value'][i]['ЗначениеСвойства'] if data['value'][i][
                                                                     'ЗначениеСвойства'] != '' else 'НЕТ'

    if flag:
        Cont.StatusDate = StatusDate
        Cont.RefJournalNum = RefJournalNum

        if send:
            DocNum = Cont.RefJournalNum
            Author_Key = dict_['Author_Key']
            date = await curent_date()
            date_obj = datetime.strptime(date, "%H:%M %d.%m.%Y")
            formatted_date = date_obj.strftime("%Y-%m-%dT%H:%M:%S")

            if DocNum == '' or DocNum == 'НЕТ':

                Alarm = dict_.get('NewErr') if dict_.get('NewErr') is not None else ''
                ic(Alarm)
                if len(Cont.LastErr) > 0 and Cont.LastErr not in ['', None, 'НЕТ', '0'] and Cont.NewErr not in ['', None, 'НЕТ', '0']:
                    Alarm = Cont.LastErr.replace(', , ', '') + ', ' + Cont.NewErr
                elif Cont.NewErr not in ['', None, 'НЕТ', '0']:
                    Alarm = Cont.NewErr
                ic(Alarm)
                long_text = {
                    "Date": formatted_date,
                    "Сотрудник_Key": Author_Key,
                    "Ответственный_Key": Author_Key,
                    "Примечание": "Created by @TmrpRefBot",
                    'Контейнеры': [{
                        "LineNumber": "1",
                        "ДатаОсмотра": formatted_date,
                        "Контейнер_Key": Cont.RefKey,
                        "МестоРазмещения": Cont.LastGPS,
                        "НормативнаяT": Cont.ReqTemp,
                        "ФактическаяT": ic(Cont.NewTemp) if Cont.NewTemp not in ['НЕТ', ''] else Cont.LastTemp,
                        "Alarm": Alarm,
                        "Груз": Cont.Cargo
                    }]
                }
                update_req = await http_rest.send_odata_post('Document_ЖурналОбходовРефов', long_text)
            else:

                text_request = {
                    "filter": "Number eq `" + DocNum + "`"}
                request = await http_rest.send_odata_get("Document_ЖурналОбходовРефов",
                                                                        text_request)
                data = request.json()

                long_text = {'Контейнеры': []}
                for i in range(len(data['value'][0]['Контейнеры'])):
                    if data['value'][0]['Контейнеры'][i]['Контейнер_Key'] == Cont.RefKey:
                        data['value'][0]['Контейнеры'][i]['Контейнер_Key'] = Cont.RefKey
                        data['value'][0]['Контейнеры'][i]['ДатаОсмотра'] = formatted_date
                        data['value'][0]['Контейнеры'][i]['МестоРазмещения'] = Cont.LastGPS
                        data['value'][0]['Контейнеры'][i]['НормативнаяT'] = Cont.ReqTemp
                        data['value'][0]['Контейнеры'][i]['ФактическаяT'] = Cont.NewTemp
                        data['value'][0]['Контейнеры'][i]['Alarm'] = Cont.NewErr
                        data['value'][0]['Контейнеры'][i]['Груз'] = Cont.Cargo
                    long_text['Контейнеры'].append(
                        {
                            'Ref_Key': data['value'][0]['Ref_Key'],
                            'LineNumber': str(data['value'][0]['Контейнеры'][i]['LineNumber']),
                            'Контейнер_Key': str(data['value'][0]['Контейнеры'][i]['Контейнер_Key']),
                            'МестоРазмещения': str(data['value'][0]['Контейнеры'][i]['МестоРазмещения']),
                            'НормативнаяT': str(data['value'][0]['Контейнеры'][i]['НормативнаяT']),
                            'ФактическаяT': str(data['value'][0]['Контейнеры'][i]['ФактическаяT']),
                            'Alarm': str(data['value'][0]['Контейнеры'][i]['Alarm']),
                            'Груз': str(data['value'][0]['Контейнеры'][i]['Груз']),
                            'ДатаОсмотра': data['value'][0]['Контейнеры'][i]['ДатаОсмотра']}
                    )

                update_req = await http_rest.send_odata_patch(
                    'Document_ЖурналОбходовРефов(guid`' + data['value'][0]['Ref_Key'] + '`)', long_text)
                ic(update_req)
            if update_req == 'Ошибка':
                await message.answer('Обновление данных конетйнера не удалось', reply_markup=ref_opt)
            elif update_req.status_code in [200, 201, 204]:
                ic('Savvvving')
                await message.message.delete()
                await state.set_state(Stat.number_cont)
                await message.message.answer('Состояние реф контейнера обновлено\nВведите номер контейнера (4 цифры)',
                                             reply_markup=ref_opt)
            else:
                await message.answer('Состояние реф контейнера не обновлено', reply_markup=ref_opt)
        elif edit:
            if not not options:
                await state.set_state(options)
            await message.message.edit_text(
                text=Cont.PrintHtml(), reply_markup=ref_control, parse_mode='HTML')
        elif type(message) == types.CallbackQuery:
            if not not options:
                await state.set_state(options)
            # await message.message.delete()
            await message.message.answer(
                text=Cont.PrintHtml(), reply_markup=ref_control, parse_mode='HTML')
            # await message.message.answer(
            #     text=Cont.PrintHtml(), reply_markup=ref_control, parse_mode='HTML')
        else:
            if not not options:
                await state.set_state(options)
            await message.answer(
                text=Cont.PrintHtml(), reply_markup=ref_control, parse_mode='HTML')
